using System.Security.Claims;
using AutoMapper;
using Core.Db.Dtos;
using Core.Db.ResourceParameters;
using Core.Db.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Core.API.Controllers;

[Route("api/orders")]
[ApiController]
public class OrdersController : ControllerBase
{
    private readonly ITouristRouteRepository _touristRouteRepository;
    private readonly IMapper _mapper;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public OrdersController(ITouristRouteRepository touristRouteRepository, IMapper mapper, IHttpContextAccessor httpContextAccessor)
    {
        _touristRouteRepository = touristRouteRepository;
        _mapper = mapper;
        _httpContextAccessor = httpContextAccessor;
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpGet]
    public async Task<IActionResult> GetOrders([FromQuery] PaginationResourceParamaters paramaters)
    {
        // 1. 获取当前用户
        var userId = _httpContextAccessor
            .HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        // 2. 使用userid 获取历史订单
        var orders = await _touristRouteRepository.GetOrdersByUserId(userId, paramaters.PageSize, paramaters.PageNumber);

        return Ok(_mapper.Map<IEnumerable<OrderDto>>(orders));
    }

    [Authorize(AuthenticationSchemes = "Bearer")]
    [HttpGet("{orderId}")]
    public async Task<IActionResult> GetOrderById([FromRoute] Guid orderId)
    {
        // 1. 获取当前用户
        var userId = _httpContextAccessor
            .HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        // 2. 使用userid 获取历史订单
        var order = await _touristRouteRepository.GetOrderById(orderId);

        return Ok(_mapper.Map<OrderDto>(order));
    }
}